<template>
  <div class="edit-pipeline">
    <div class="header">
      <div class="title">
        <span class="title-text">编辑流水线</span>
        <span class="title-icon" @click="starPipeline">
          <SvgIcon class="iconDef" name="star" :color="starColor" width="16" height="16" />
        </span>
      </div>
      <div class="tabs">
        <TabsCard :current-tab="activeTab" @change-tab="changeTab" :tabList="tabList" />
      </div>
      <div class="btn-list">
        <a-button class="default-button btn-font" :loading="saveAndRunLoading" @click="saveAndRun" v-if="!isView">
          <template #icon>
            <SvgIcon name="play-save" width="16" height="16" />
          </template>
          保存并运行
        </a-button>
        <a-button type="primary" class="default-button" :loading="onlySaveLoading" @click="onlySave" v-if="!isView">
          <template #icon>
            <save-outlined />
          </template>
          仅保存</a-button
        >
        <a-button class="default-button btn-font" @click="back">
          <template #icon>
            <SvgIcon name="left-arrow" width="16" height="16" />
          </template>
          返回</a-button
        >
      </div>
    </div>
    <div :style="{ boxShadow: '0px 1px 0px 0px #e7eff8', width: '100%' }"></div>
    <div v-if="activeTab === 'flowChoreography'" class="flowChoreography-content">
      <flowChoreography />
    </div>
    <div v-if="activeTab === 'baseInfo'" class="box-content">
      <baseInfo />
    </div>
    <div v-if="activeTab === 'triggerSetting'" class="box-content">
      <triggerSetting />
    </div>
    <div v-if="activeTab === 'variablesAndCache'" class="box-content">
      <variablesAndCache />
    </div>
  </div>
</template>
<script setup lang="ts">
import { message } from 'ant-design-vue';
import flowChoreography from './components/flowChoreography.vue';
import baseInfo from './components/baseInfo.vue';
import triggerSetting from './components/triggerSetting.vue';
import variablesAndCache from './components/variablesAndCache.vue';
import { SaveOutlined } from '@ant-design/icons-vue';
import { usePipelineStore } from '@/store/modules/pipeline';
import { updatePipeline } from '@/api/pipeline';
import { PipelineOperationTypeCode, TriggType, TimeTriggeredType } from '@/enums/pipelineEnum';
import { usePipeline } from '../pipelineHooks';
const { pipelineCode, starPipeline, fetchPipelineInfo, starColor } = usePipeline();
import * as CryptoUtils from '@/utils/cryptoUtils';

// import { baseInfoData, triggerSettingData, variableSettingListData, cacheSettingListData } from './data';
const pipelineStore = usePipelineStore();
// const { setBaseInData, setTriggerSettingsData, setVariablesData, setCacheDataData } = pipelineStore;
const activeTab = ref('flowChoreography');
const router = useRouter();
const route = useRoute();
provide('store', pipelineStore);
const onlySaveLoading = ref(false);
const saveAndRunLoading = ref(false);
const changeTab = (key: string) => {
  activeTab.value = key;
};
const isView = computed(() => route.params.type == PipelineOperationTypeCode.info);
const tabList = ref([
  {
    key: 'baseInfo',
    tab: '基本信息',
  },
  {
    key: 'flowChoreography',
    tab: '流程编排',
  },
  {
    key: 'triggerSetting',
    tab: '触发设置',
  },
  {
    key: 'variablesAndCache',
    tab: '变量与缓存',
  },
]);

const back = () => {
  router.go(-1);
};

onMounted(async () => {
  pipelineCode.value = route.params.code as string;
  await pipelineStore.fetchPipelineConfigData(route.params.code as string);
  await fetchPipelineInfo();
  // await pipelineStore.fetchPipelineConfigData('80e82e2a2d394d65a701ebb4d5e7689c');
});

const messageText = ref('校验未通过');
const validate = () => {
  const hasErrorValidate = pipelineStore.getFlowChoreographyData.find((item: Pipeline.Task) => item.isValidateError);
  const baseInfoValidate = pipelineStore.getBaseInfoData.name === '';
  const triggerSettingValidate = pipelineStore.getTriggerSettingsData;
  if (hasErrorValidate) {
    changeTab('flowChoreography');
    return false;
  }
  if (triggerSettingValidate.isClockTrigger == TimeTriggeredType.open) {
    if (!triggerSettingValidate.triggerWay) {
      messageText.value = '请选择触发时间';
      changeTab('triggerSetting');
      return false;
    }

    // 单个触发时间验证
    if (triggerSettingValidate.triggerWay == TriggType.singleTime) {
      if (!triggerSettingValidate.triggerTime) {
        messageText.value = '请选择触发时间';
        changeTab('triggerSetting');
        return false;
      }
    }
    // 周期触发时间验证
    if (triggerSettingValidate.triggerWay == TriggType.cycle) {
      if (!triggerSettingValidate.weekDay || !triggerSettingValidate.periodTriggerTime) {
        messageText.value = '请选择触发时间';
        changeTab('triggerSetting');
        return false;
      }
    }
  }
  if (baseInfoValidate) {
    changeTab('baseInfo');
    return false;
  }
  return true;
};

const onlySave = async () => {
  if (!validate()) {
    message.error(messageText.value);
    messageText.value = '校验未通过';
    return;
  }
  try {
    onlySaveLoading.value = true;
    await updatePipeline({
      ...pipelineStore.getAllData,
      taskList: pipelineStore.getFlowChoreographyData.map((item: Pipeline.Task) => ({
        ...item,
        schema: '',
        params: CryptoUtils.encryptByRSA(JSON.stringify(item.params)) || item.params,
      })),
      ifRunPipeline: false,
    });
    message.success('保存成功');
  } finally {
    onlySaveLoading.value = false;
  }
};

const saveAndRun = async () => {
  if (!validate()) {
    message.error(messageText.value);
    messageText.value = '校验未通过';
    return;
  }
  try {
    saveAndRunLoading.value = true;
    await updatePipeline({
      ...pipelineStore.getAllData,
      taskList: pipelineStore.getFlowChoreographyData.map((item: Pipeline.Task) => ({
        ...item,
        schema: '',
        params: CryptoUtils.encryptByRSA(JSON.stringify(item.params)) || item.params,
      })),
      ifRunPipeline: true,
    });
    message.success('保存并运行成功');
    router.push(`/system/pipelineRunning/${route.params.code as string}`);
  } finally {
    saveAndRunLoading.value = false;
  }
};

// 销毁页面时清除缓存
onUnmounted(() => {
  pipelineStore.setFlowChoreographyData([] as Pipeline.Task[]);
  pipelineStore.setBaseInData({} as Pipeline.BaseInfo);
  pipelineStore.setTriggerSettingsData({} as Pipeline.TriggerSetting);
  pipelineStore.setVariablesData([] as Pipeline.VariableSetting[]);
  pipelineStore.setCacheDataData([] as Pipeline.CacheSetting[]);
});
</script>
<style lang="less" scoped>
.edit-pipeline {
  background-color: #fff;
  height: 100%;
  .header {
    height: 60px;
    box-shadow: 0px 1px 0px 0px rgba(231, 239, 248, 1);
    border-radius: 4px 4px 0px 0px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 0 40px;
    .title {
      font-weight: 400;
      width: fit-content;
      display: flex;
      align-items: center;
      &-text {
        font-size: 24px;
        color: rgba(0, 0, 0, 0.8);
      }
      &-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        margin-left: 10px;
        cursor: pointer;
      }
      &::after {
        content: '';
        display: inline-block;
        width: 1px;
        height: 24px;
        margin-left: 24px;
        background-color: #e7eff8;
      }
    }
    .tabs {
      flex: 1;
      margin-left: 20px;
    }
    .btn-list {
      display: flex;
      align-items: center;
      justify-content: end;
      gap: 16px;
      .default-button {
        border: 1px solid rgba(216, 232, 248, 1);
        border-radius: 4px;
        font-size: 14px;
        font-weight: 400;
        display: flex;
        align-items: center;
      }
      .btn-font {
        color: #2590ff;
        gap: 8px;
      }
    }
  }
  .flowChoreography-content {
    margin-top: 2px;
    padding: 20px 40px;
    background-color: #fff;
    border-radius: 0 0 4px 4px;
    height: calc(100% - 62px);
  }
  .box-content {
    margin-top: 2px;
    padding: 0 40px;
    background-color: #fff;
    border-radius: 0 0 4px 4px;
    height: calc(100% - 62px);
  }
}
</style>
